// -----------------------------------------------------------
// Game Framework
// Copyright © 2024-2024 deadcycle. All rights reserved.
// Homepage: https://deadcycle.gitee.io
// Feedback: deadcycle@163.com
// -----------------------------------------------------------

using System.Collections.Generic;

using UnityEngine;
using UnityEngine.UI;

namespace UIWidget
{
    /// <summary>
    /// 镜像翻转效果, 用于扩展Graphic组件。
    /// </summary>
    [RequireComponent(typeof(Graphic)), DisallowMultipleComponent]
    public class FlipMeshEffect : BaseMeshEffect
    {
        #region 字段
        /// <summary> 水平镜像翻转。 </summary>
        [SerializeField]
        private bool m_HorizontalFlip;

        /// <summary> 垂直镜像翻转。 </summary>
        [SerializeField]
        private bool m_VerticalFlip;

        /// <summary> 顶点缓存容器。 </summary>
        private static readonly List<UIVertex> s_CacheUIVertices = new List<UIVertex>();
        #endregion

        public override void ModifyMesh(VertexHelper vh)
        {
            if (!IsActive())
            {
                return;
            }

            if (!m_HorizontalFlip && !m_VerticalFlip)
            {
                Debug.LogWarning("FlipMeshEffect has not been modified. (添加了镜像翻转效果, 但无翻转设置)");

                return;
            }

            s_CacheUIVertices.Clear();

            // 从顶点辅助器中加载顶点信息到缓存容器
            vh.GetUIVertexStream(s_CacheUIVertices);

            UpdateFlipEffect();

            // 清理网格数据
            vh.Clear();
            vh.AddUIVertexTriangleStream(s_CacheUIVertices);

            s_CacheUIVertices.Clear();
        }

        /// <summary>
        /// 根据翻转条件, 处理顶点数据信息。
        /// </summary>
        private void UpdateFlipEffect()
        {
            Vector2 pivot = graphic.rectTransform.rect.center;

            for (int i = 0; i < s_CacheUIVertices.Count; i++)
            {
                UIVertex vertex = s_CacheUIVertices[i];

                if (m_HorizontalFlip && m_VerticalFlip)
                {
                    vertex.position.x = 2 * pivot.x - vertex.position.x;
                    vertex.position.y = 2 * pivot.y - vertex.position.y;
                }
                else if (m_HorizontalFlip)
                {
                    vertex.position.x = 2 * pivot.x - vertex.position.x;
                }
                else if (m_VerticalFlip)
                {
                    vertex.position.y = 2 * pivot.y - vertex.position.y;
                }

                s_CacheUIVertices[i] = vertex;
            }
        }
    }
}